<template>
    <div class="search">
        <van-search
                v-model="msg"
                show-action
                placeholder="请输入搜索关键词"
                @search="getSearchRes()"
                shape="round"
                background="rgb(65,112,118)"
        >
            <template #action>
                <div @click="getSearchRes()" style="color: #fff;font-size: 17rem">搜索</div>
            </template>
        </van-search>
    </div>
    <div class="result">
        <van-list>
            <van-cell v-for="(item,index) in songsList" :key="index">
                <div class="van-cell">
                    <p>{{item.name }}</p>
                    <van-icon name="play-circle-o" v-if="item.name !== store.state.musicName" @click="goPlay(item.id,item.name,item.artists)"/>
                    <van-icon name="pause-circle-o" v-if="item.name === store.state.musicName" @click="[goPlay(item.id,item.name,item.artists)]"/>
                </div>
            </van-cell>
        </van-list>
    </div>
</template>

<script setup>
    import axios from "axios";
    import {ref, toRefs} from 'vue';
    import {useStore} from 'vuex';
    import {Toast} from 'vant';
    import 'aplayer/dist/APlayer.min.css';
    import APlayer from 'aplayer';

    //输入框和搜索数据内容双向绑定
    const msg = ref()
    const songsList = ref([])
    const store = useStore();
    const flag = ref(false)
    //定义搜索功能
    const onSearch = (val) => Toast(val);
    const getSearchRes = async function () {
        try {
            //遮罩层
            Toast.loading({
                message: '加载中...',
                forbidClick: true,
                duration: 0,
                overlay: true
            })
            if (msg.value === undefined) {
                return
            } else {
                const res = await axios.get(`https://koo-music.vercel.app/search?keywords=${msg.value}`)
                songsList.value = res.data.result.songs
            }
        } catch (e) {} finally {
            Toast.clear()
        }
    }
    const goPlay = (id, name, artists) => {
        store.commit('getMusicUrl', {id, name, artists})
        const ap = new APlayer({
            container: document.getElementById('aplayer'),
            autoplay:true,
            audio: [{
                name: store.state.musicName,
                artist: store.state.musicArtists,
                url: store.state.musicUrl,
                theme: '#FADFA3'
            }]
        });
    }

    /*const playAudio = (id)=>{
         this.musicUrl = `https://music.163.com/song/media/outer/url?id=${id}.mp3`
     }*/
</script>

<style scoped>


    .van-cell {
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-size: 20rem;
        background-color: honeydew;
        color: dimgrey;
    }

</style>